package com.security.springcloud.uaa.dao;

import com.security.springcloud.uaa.model.PermissionDTO;
import com.security.springcloud.uaa.model.UserDTO;
import com.sun.istack.internal.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yingyuwei
 * @version 1.0.0
 * @description TODO
 * @createTime 2021年02月28日 13:46:00
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public UserDTO queryByUsername(@NotNull String username) {
        String sql = " select * from t_user where username = ? ";
        List<UserDTO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(UserDTO.class), new Object[]{username});
        if (list != null && list.size() == 1) {
            return list.get(0);
        }

        return null;
    }

    public List<String> queryPermissionByUserId(String userId) {
        StringBuilder sql = new StringBuilder();
        sql.append(" select * from t_permission t1, t_role_permission t2, t_role t3, t_user_role t4 , t_user t5");
        sql.append(" where t1.id = t2.permission_id and t2.role_id = t3.id and t3.id = t4.role_id and t4.user_id = t5.id");
        sql.append(" and t5.id = ?");
        List<PermissionDTO> permissions = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(PermissionDTO.class), new Object[]{userId});
        if (!CollectionUtils.isEmpty(permissions)) {
            return permissions.stream().map(PermissionDTO::getCode).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}
